#include <rtthread.h>
#include "stm32h745i_discovery_sdram.h"

struct rt_memheap sdram_heap;

int sdram_init()
{
    if (BSP_SDRAM_Init(0) != BSP_ERROR_NONE) {
        rt_kprintf("SDRAM Init failed!\n");
        return -1;
    }

    rt_err_t err = rt_memheap_init(&sdram_heap, "sdram", (void*) SDRAM_DEVICE_ADDR, SDRAM_DEVICE_SIZE);
    if (err != RT_EOK) {
        rt_kprintf("init sdram memheap failed!\n");
        return -1;
    }
    return 0;
}
INIT_DEVICE_EXPORT(sdram_init);

int test_sdram(int argc, char* argv[])
{
    rt_uint8_t* sdram_addr = (rt_uint8_t*) SDRAM_DEVICE_ADDR;
    volatile rt_uint8_t* wp = sdram_addr;
    rt_kprintf("Write SDRAM ...\n");
    rt_uint32_t start_tick = rt_tick_get();
    for (rt_uint32_t i = 0; i < SDRAM_DEVICE_SIZE; i++) {
        *wp++ = (i & 0xFF);
    }
    rt_uint32_t cost_tick = rt_tick_get() - start_tick;
    rt_kprintf("Write SDRAM done, cost %d ticks!\n", cost_tick);

    volatile rt_uint8_t* rp = sdram_addr;
    rt_kprintf("Read SDRAM ...\n");
    start_tick = rt_tick_get();
    for (rt_uint32_t i = 0; i < SDRAM_DEVICE_SIZE; i++) {
        if (*rp != (i & 0xFF)) {
            rt_kprintf("[%p] check fail %02X %02X\n", rp, *rp, (i & 0xFF));
        }
        rp++;
    }
    cost_tick = rt_tick_get() - start_tick;
    rt_kprintf("Read SDRAM done, cost %d ticks!\n", cost_tick);
    return 0;
}
MSH_CMD_EXPORT(test_sdram, test SDRAM);